package com.study.login;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.study.entity.User;
import com.study.service.IUserService;
import com.study.service.impl.UserServiceImpl;
import com.study.util.NoUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    private static final Log log = LogFactory.get();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendRedirect(request.getContextPath() + "/register.jsp");
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String userName = request.getParameter("userName");
        String userMobile = request.getParameter("userMobile");
        String password = request.getParameter("password");

        log.info("注册用户【{}】,注册手机号【{}】,登录密码【{}】",userName,userMobile,password);

        //判断用户是否提交了账号密码
        if (StrUtil.isBlankIfStr(userName) || StrUtil.isBlankIfStr(userMobile) || StrUtil.isBlankIfStr(password)){
            request.setAttribute("message","账号|手机号|密码|不能为空!");
            request.getRequestDispatcher("/fail.jsp").forward(request,response);
            return;
        }

        //判断用户名是否已经存在
        IUserService userService = new UserServiceImpl();
        User userFlag = userService.selectUserByUserName(userName);

        if (userFlag != null){
            request.setAttribute("message","账号["+userName+"]已经存在,请更换账号");
            request.getRequestDispatcher("/fail.jsp").forward(request,response);
            return;
        }

        //创建用户
        User user = new User();
        //获取用户的编号
        int no = userService.selectMaxId();
        //构建实体
        user.setUserNo(NoUtil.getNo("U",no));
        user.setUserName(userName);
        user.setUserMobile(userMobile);
        user.setUserPassword(password);
        //注册用户
        int row = userService.registerUser(user);

        if (row > 0){
            //账号密码正确,跳转到成功页面
            request.setAttribute("message","注册成功!");
            request.getRequestDispatcher("/success.jsp").forward(request,response);
        }else {
            request.setAttribute("message","账号注册失败,请联系管理员");
            request.getRequestDispatcher("/fail.jsp").forward(request,response);
        }


    }
}
